package top.abilities.util.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
* @Description: 资源文件读取工具
* @Author abilites
* @Date 2017/9/20 15:46
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {

   private static ApplicationContext context = null;

   private SpringContextUtil() {
       super();
   }

   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
       context = applicationContext;
   }

    /**
     * @Description: 根据名称获取bean
     * @Param: [beanName]
     * @Return java.lang.Object
     * @Author abilites
     * @Date 2017/9/20 15:47
     */
   public static Object getBean(String beanName) {
       return context.getBean(beanName);
   }

    /**
     * @Description: 根据bean名称获取指定类型bean
     * @Param: [beanName]  bean名称
     * @Param: [clazz]  返回的bean类型,若类型不匹配,将抛出异常
     * @Return T
     * @Author abilites
     * @Date 2017/9/20 15:48
     */
   public static <T> T getBean(String beanName, Class<T> clazz) {
       return context.getBean(beanName, clazz);
   }
    /**
     * @Description: 根据类型获取bean
     * @Param: [clazz]
     * @Return T
     * @Author abilites
     * @Date 2017/9/20 15:49
     */
   public static <T> T getBean(Class<T> clazz) {
       T t = null;
       Map<String, T> map = context.getBeansOfType(clazz);
       for (Map.Entry<String, T> entry : map.entrySet()) {
           t = entry.getValue();
       }
       return t;
   }
    /**
     * @Description: 是否包含bean
     * @Param: [beanName]
     * @Return boolean
     * @Author abilites
     * @Date 2017/9/20 15:50
     */
   public static boolean containsBean(String beanName) {
       return context.containsBean(beanName);
   }

   /**
    * 是否是单例
    * @param beanName
    * @return
    */
   public static boolean isSingleton(String beanName) {
       return context.isSingleton(beanName);
   }

   /**
    * bean的类型
    * @param beanName
    * @return
    */
   public static Class getType(String beanName) {
       return context.getType(beanName);
   }

}
